/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package server;

import java.net.*;
import java.util.*;

import message.*;
import message.handler.*;
import util.QueueMonitor;

import java.util.Queue;

/**
 *
 * @author kinder
 */

public class Server {
    
    public static void main(String args[])throws Exception
    {
        Queue<Message> messagesQueue = new LinkedList<Message>();
        QueueMonitor monitor = new QueueMonitor(messagesQueue);

        ServerSocket server = new ServerSocket(7777);

        RunnableConsumer consumer = new RunnableConsumer(monitor);
        Thread tpoll = new Thread(consumer);
        tpoll.start();

        while(true)
        {
            Socket connessioneServer = server.accept();
            RunnableServer sessione = new RunnableServer(connessioneServer, monitor);
            Thread t = new Thread(sessione);
            t.start();
        }

    }

}

    class RunnableConsumer implements Runnable{

        private QueueMonitor monitor;
        private MessageHandlerFactory messageHandler;

        public RunnableConsumer(QueueMonitor monitor)
        {
            this.monitor = monitor;
            this.messageHandler = new MessageHandlerFactory();
        }

        public void run()
        {
            while(true)
            {
                Message m = this.monitor.dequeue();
                try{
                    Thread.sleep(300);
                }
                catch(InterruptedException e){
                    e.printStackTrace();
                }

                try{
                MessageHandler handler = this.messageHandler.getHandlerForType(m.getId());
                handler.handleMessage(m);
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
                
            }
        }
    }

